<?php

namespace app\admin\service\common\permission;

use app\admin\model\admin\User as UserModel;
use app\common\Constants;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class PermissionService
{
    private const SCOPE_MAP = [
        5 => Constants::DATA_SCOPE_SELF,
        4 => Constants::DATA_SCOPE_DEPT_CURRENT,
        3 => Constants::DATA_SCOPE_DEPT_AND_SUB,
        2 => Constants::DATA_SCOPE_DEPT_CUSTOM,
        1 => Constants::DATA_SCOPE_ALL,
    ];

    public function __construct(
        protected MaxDataPermissionResolver $maxResolver,
        protected MinDataPermissionResolver $minRresolver,
    )
    {
    }

    public function getUserDataPermission(int $userId): array
    {
        // $cacheKey = Constants::CACHE_USER_DATA_PERMISSION_PREFIX . $userId;
        // $dataPermission = Cache::get($cacheKey);

        $dataPermission = [];
        if (empty($dataPermission)) {
            $user = UserModel::find($userId);
            if (!$user) return [];

            // 获取用户所有角色及其数据权限
            $roles = $user->roles()->select();
            trace(json_encode($roles),'用户角色数据');

            // 提取角色权限数据
            $rolePermissions = [];

            foreach ($roles as $role) {
                $permType = self::SCOPE_MAP[$role->scope] ?? Constants::DATA_SCOPE_NONE;
                $permData = ['type' => $permType];

                // 如果是自定义权限，获取关联的部门ID
                $permData['custom_dept_ids'] = [];
                if ($permType === Constants::DATA_SCOPE_DEPT_CUSTOM && $role['dept_ids']) {
                    $permData['custom_dept_ids'] = array_unique(array_merge($permData['custom_dept_ids'],$role['dept_ids']));
                }
                $rolePermissions[] = $permData;
            }

            if(strtolower(config('rds.scope_mode')) === 'max') {
                // 使用最大权限解析器
                $finalPermission = $this->maxResolver->resolve($rolePermissions);
            } else {
                // 使用最小权限解析器
                $finalPermission = $this->minRresolver->resolve($rolePermissions);
            }

            $dataPermission = [
                'data_permission_type' => $finalPermission['type'],
                'custom_dept_ids' => $finalPermission['custom_dept_ids'] ?? [],
                'dept_id' => $user->dept_id
            ];

            // Cache::set($cacheKey, $dataPermission, Constants::CACHE_PERMISSION_TTL);

        }
        return $dataPermission;

    }

    public function clearUserPermissionCache(int $userId): void
    {
        Cache::delete(Constants::CACHE_USER_PERMISSION_PREFIX . $userId);
        Cache::delete(Constants::CACHE_USER_DATA_PERMISSION_PREFIX . $userId);
    }

    public function getUserPermissions(int $userId): array
    {

        // $cacheKey = Constants::CACHE_USER_PERMISSION_PREFIX . $userId;
        // $permissions = Cache::get($cacheKey);

        $permissions = [];
        $front_permissions = [];
        if (empty($permissions)) {
            // 是否是超级用户
            if($userId === Constants::SUPER_USER_ID) {
                // 超级用户具有完全权限，所以，只把菜单通配符权限加入即可
                $action_codes = [];
                $menu_codes = Db::name('dev_menu')
                    ->where('status',1)
                    ->column('code');
            } else {
                // 查看用户是否存在
                $user = UserModel::find($userId);
                if (!$user) return [];

                // 查询此用户功能权限
                $action_codes = Db::name('dev_action')->alias('a')
                    ->join('admin_role_action ra', 'a.id = ra.action_id')
                    ->join('admin_role_user ru', 'ra.role_id = ru.role_id')
                    ->where('ru.user_id', $userId)
                    ->distinct(true)
                    ->column('a.code');
                // 获取此用户菜单权限
                $menu_codes = Db::name('dev_menu')->alias('m')
                    ->join('admin_role_menu rm', 'm.id = rm.menu_id')
                    ->join('admin_role_user ru', 'rm.role_id = ru.role_id')
                    ->where('ru.user_id', $userId)
                    ->distinct(true)
                    ->column('m.code');
            }

            // 前端兼容，去重，去空，合并
            $permissions = array_values(array_unique(array_filter(array_merge($action_codes, $menu_codes))));

            // Cache::set($cacheKey, $permissions, Constants::CACHE_PERMISSION_TTL);
        }

        return ['perms' => $permissions];
    }
}